from .celery import app
from ldap3 import Server, Connection, ALL, SUBTREE, ServerPool, ALL_ATTRIBUTES, NTLM, Tls
from apps.account.models import LoonUser
from settings import config
from django.core.cache import cache


@app.task
def ldap_sync_user(ldap_attr):
    conn = Connection(config.MY_LDAP_SERVER_URI, user=config.MY_LDAP_BIND_DN, password=config.MY_LDAP_BIND_PASSWORD,
                      check_names=True, lazy=False, raise_exceptions=False, read_only=False)
    conn.open()
    conn.bind()

    res = conn.search(
        search_base=config.MY_LDAP_SEARCH_BASE,
        # search_filter='(cn=*)',  # 查询所有用户
        search_filter='(objectclass=user)',  # 查询所有用户
        search_scope=SUBTREE,
        attributes=['cn', 'sn', 'givenName', 'mail', 'sAMAccountName', 'distinguishedName']
        # cn用户中文名，sn姓，givenName名，mail邮件，sAMAccountName是账号
    )
    # print(res)
    if res:
        # count = 0
        for entry in conn.response:
            dict_attr = entry['attributes']
            # has_user = models.User.query.filter_by(username=dict_attr['cn']).first()
            has_user = LoonUser.objects.filter(username=dict_attr['cn']).first()
            dept = dict_attr['distinguishedName'].split(',')[1].split('=')[1]

            if dept.startswith('ops'):
                dept_id = 1
            elif dept.startswith('dev'):
                dept_id = 2
            else:
                dept_id = 3
            # print('用户名：', dict_attr['cn'], '所属部门:', dept, '部门id:',dept_id)
            # print(has_user)
            if not has_user:
                user_form_dict = {}
                for db_filed, ldap_fied in ldap_attr.items():

                    if ldap_fied == "mail":

                        if dict_attr.get(ldap_fied):

                            email = dict_attr.get(ldap_fied)
                        else:

                            email = f"{dict_attr.get('cn')}@bybit.com"

                        user_form_dict[db_filed] = email
                    else:
                        user_form_dict[db_filed] = dict_attr.get(ldap_fied, None)
                user = LoonUser
                user.objects.update_or_create(username=dict_attr['cn'], alias=dict_attr['sn'], email=email,
                                              dept_id=dept_id)
